package com.dc.aspect;


import com.dc.dao.IpLogRepository;
import com.dc.po.IpLog;
import com.dc.service.IpLogService;
import com.dc.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j //日志注解
@Aspect
@Component
public class LogAspect {

    @Autowired
    private IpLogService ipLogService;

    @Autowired
    private IpLogRepository ipLogRepository;

//    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.dc.web..*(..) )")
    public void log() {
    }

    /**
     * 记录日志内容：
     * 请求 url
     * 访问者 ip
     * 调用方法 classMethod
     * 参数 args
     *
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        System.out.println("---------doBefore-----------");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        log.info("Request : {}", requestLog);
        boolean isFooter = url.contains("footer");
        boolean isSafeIp = "183.6.172.114".equals(ip);
        boolean isAddBlog = url.contains("/admin/blogs");
        if (!isFooter) {
            if(isAddBlog||isSafeIp){
                return;
            }
            String ipMsg = IpUtils.getIpMsg(ip);
            ipLogService.saveIpLog(IpLog.builder().
                    ip(ip).url(url).classMethod(classMethod).args(Arrays.toString(args)).ipMsg(ipMsg).time(new Date()).build());
        }
    }

    @After("log()")
    public void doAfter() {
//        System.out.println("---------doAfter-----------");

    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAtfertReturning(Object result) {
//        logger.info("Return ------ {}",result );
    }


    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }


}
